import deptApi from '@/api/deptApi'
import userApi from '@/api/userApi'
import type { DeptItem } from '@/types/deptType'
import type { IAction, IModalProps } from '@/types/modal'
import type { UserItem } from '@/types/userType'
import { Form, Input, message, Modal, Select, TreeSelect } from 'antd'
import { useEffect, useImperativeHandle, useState } from 'react'

const CreateDept = (props: IModalProps<DeptItem>) => {
  const [visible, setVisible] = useState(false)
  const [data, setData] = useState<DeptItem[]>([])
  const [form] = Form.useForm()
  const [action, setAction] = useState<IAction>('create')
  const [userList, setUserList] = useState<UserItem[]>([])
  const getDeptList = async () => {
    const res = await deptApi.getDeptList()
    setData(res)
  }
  const getAllUserList = async () => {
    const res = await userApi.getAllUserList()
    setUserList(res)
  }
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  useEffect(() => {
    getAllUserList()
  }, [])
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const open = (type: IAction, data: any) => {
    getDeptList()
    setAction(type)
    if (data) {
      form.setFieldsValue(data)
    }
    setVisible(true)
  }
  const handleCancel = () => {
    setVisible(false)
    form.resetFields()
  }
  const handleSubmit = async () => {
    await form.validateFields()
    const params = form.getFieldsValue(true)
    if (action === 'create') {
      await deptApi.createDept(params)
      message.success('创建成功')
    }
    if (action === 'edit') {
      await deptApi.editDept(params)
      message.success('编辑成功')
    }
    props.update()
    handleCancel()
  }
  return (
    <Modal
      width={800}
      open={visible}
      title={action === 'create' ? '新增部门' : '编辑部门'}
      onOk={handleSubmit}
      onCancel={handleCancel}
      okText='确定'
      cancelText='取消'
    >
      <Form form={form} labelCol={{ span: 4 }}>
        <Form.Item label='上级部门' name='parentId'>
          <TreeSelect
            fieldNames={{ label: 'deptName', value: '_id' }}
            showSearch
            style={{ width: '100%' }}
            styles={{
              popup: { root: { maxHeight: 400, overflow: 'auto' } }
            }}
            placeholder='请选择上级部门'
            treeData={data}
            allowClear
            treeDefaultExpandAll
          />
        </Form.Item>
        <Form.Item label='部门名称' name='deptName' rules={[{ required: true, message: '请输入部门名称' }]}>
          <Input placeholder='请输入部门名称'></Input>
        </Form.Item>
        <Form.Item label='负责人' name='userName' rules={[{ required: true, message: '请选择负责人' }]}>
          <Select
            placeholder='请选择负责人'
            options={userList}
            fieldNames={{ label: 'userName', value: 'userName' }}
          ></Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateDept
